﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KDG.FoldersSize.Scaner;

namespace KDG.FoldersSize
{
    /// <summary>
    /// Interaction logic for FindDublicates.xaml
    /// </summary>
    public partial class FindDublicates : UserControl
    {
        //ScannerItem root = null;

        public FindDublicates()
        {
            InitializeComponent();
        }

        public ScannerItem RootNode { get; set; }
        //public void SetRoot(ref ScannerItem Root) { root = Root; }


        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            if (RootNode == null)
                return;

            List<ScannerItem> list = new List<ScannerItem>();
            Action<ScannerItem> find = null;
            find = new Action<ScannerItem>((x) =>
            {
                list.Add(x);
                if (x.Childs != null)
                    x.Childs.ForEach(c => find(c));

            });
            find(RootNode);

            list.Sort((x, y) =>
            {
                if (x.Name.Equals(y.Name))
                    return 0;

                return 1;
            });

            List<FileDublicate> fdl = new List<FileDublicate>();

            foreach (ScannerItem si in list)
            {
                FileDublicate f1 = fdl.FirstOrDefault(x => x.Name.Equals(si.Name));
                if (f1 != null)
                    f1.Dublucates.Add(si.FullName);
                else
                    fdl.Add(new FileDublicate() { Name = si.Name, FullPath = si.FullName });
            }

            fdl.RemoveAll(x => x.DublucatesCount < 2);

            fdl.ForEach((x) =>
            {
                ListBoxItem lbi = new ListBoxItem();
                lbi.DataContext = x;
                lbDublicates.Items.Add(lbi);
            });

        }
    }
}
